<?php
// +----------------------------------------------------------------------
// | 管理员模块业务逻辑
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\admin\service;

use app\common\model\SysUserModel;
use think\captcha\facade\Captcha;
use Firebase\JWT\JWT;

class SysUserService{

    /**
     * 新增数据
     * @param  array  $data  新增的数据
     * @return json
     */
    public static function save($data){
        if(SysUserModel::getByAccount($data['account'])){
            //如果存在
            return failure(config('error.er8')['code'],config('error.er8')['msg']);
        }

        $data['password'] = createPassword($data['password']);
        $result = SysUserModel::create($data);
        return success($result->id);
    }

    /**
     * 更新数据
     * @param  array  $data  更新的数据
     * @return json
     */
    public static function update($data){
        $sysUser = SysUserModel::find($data['id']);
        if(!$sysUser){
            return failure(config('error.er15')['code'],config('error.er15')['msg']);
        }

        //如果提交过来的账号跟数据库记录的账号不一样，说明当前提交过来的账号是修改过后的账号，因此这里需要验证码修改过的账号是否在数据库里面已经存在
        if(isset($data['account']) && $data['account'] !== $sysUser->account){
            if(SysUserModel::getByAccount($data['account'])){
                //如果存在
                return failure(config('error.er8')['code'],config('error.er8')['msg']);
            }
        }

        //加密
        if(isset($data['password']) && !empty($data['password'])){
            $data['password'] = createPassword($data['password']);
        }

        $sysUser->save($data);

        return success($sysUser->id);
    }

    /**
     * 分页
     * @param  array  $param  请求参数
     * @return array
     */
    public static function page($param){
        $data = SysUserModel::page($param,['withoutField'=>'password']);

        $roleIds = array_column($data, 'role_id');
        $roles = SysRoleService::listById($roleIds);

        foreach ($data['list']  as $k => $v) {
            $data['list'][$k]['role_name'] = '';
            foreach ($roles as $value) {
                if ($v['role_id'] == $value['id']) {
                    $data['list'][$k]['role_name'] = $value['role_name'];
                }
            }
        }

        return success($data);
    }

    

    /**
     * 删除
     * @param  string  $ids     需要删除数据的id
     */
    public static function destroy($ids){
        if(!empty($ids)){
            SysUserModel::deleteById($ids);
        }
    }

    /**
     * 详情
     * @param  string  $id   用户ID
     */
    public static function info($id){
        $user = SysUserModel::withoutField('password')->find($id)->toArray();
        $user['menu'] = [];
        if($user['root'] == 1){
            //如果是超级管理员，直接返回所有菜单
            $user['menu'] = SysMenuService::list();
        }else{
            if($user['roles']){
                $authIds = SysRoleService::getAuths($user['roles']);
                $user['menu'] = SysMenuService::listById($authIds);
            }
        }

        return success($user);
    }

    /**
     * 创建图片验证码
     * @return array
     */
    public static function createCaptcha(){
        $uniqid = uniqid(rand(00000,99999));
        $rs = Captcha::create();
        $base64_image = "data:image/png;base64," . base64_encode($rs->getData());
        $key = session('captcha.key');

        cache(config('redisKey.ADMIN_LOGIN_VERIFY_').$uniqid,$key);

        return success(['uniqid'=>$uniqid,'image'=>$base64_image]);
    }

    /**
     * 用户登录
     * @param  array  $data  请求参数
     * @return array
     */
    public static function login($data){
        $user = SysUserModel::getByAccount($data['account']);
        if(empty($user) || !comparePassword($data['password'],$user['password'])){
            //账号或者密码错误
            return failure(config('error.er11')['code'],config('error.er11')['msg']);
        }

        if($user['status'] == 0){
            //账号被禁用
            return failure(config('error.er12')['code'],config('error.er12')['msg']);
        } 
       
        //下面是验证成功后的处理逻辑
        //登录成功后更新用户信息
        $user->login_time = date('Y-m-d H:i:s',time());
        $user->login_ip = getClientIp();
        $user->save();

        //生成token
        $token = $user->toArray();
        //一天后过期
        $token['exp'] = time() + 24*3600;
       
        $jwt = JWT::encode($token,config('app.jwt_code_admin'),"HS256");

        return success(['token' => $jwt]);
    }

}